#ifndef __CLIENT_COMMON_DBHELPER_included
#define __CLIENT_COMMON_DBHELPER_included

#include <string>
#include <boost/shared_ptr.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <sqlite3.h>
#include "Record.h"
#include "../port/System.h"

using namespace std;

namespace Client {
namespace Common {

class CSQLiteDBWrapper;

class CDBCursor {

	boost::shared_ptr<CSQLiteDBWrapper> mDB;
	sqlite3_stmt* mStatement;
	int mCount;

public :

	CDBCursor(boost::shared_ptr<CSQLiteDBWrapper> db, sqlite3_stmt* stmt, int count) : 
	   mStatement(stmt), mDB(db), mCount(count) 
	{ }

	bool Step() {
		return sqlite3_step(mStatement) == SQLITE_ROW;
	}

	void GetString(int col, string& s) {
		const char* p = (const char*)sqlite3_column_text(mStatement, col);
		if(p) s = p;
		else s = "";
	}

	void GetInt(int col, int& v) {
		v = sqlite3_column_int(mStatement, col);
	}

	void GetInt64(int col, Util::CSystem::Int64& v) {
		v = sqlite3_column_int64(mStatement, col);
	}

	int GetCount() {
		return mCount;
	}

	void Reset() {
		sqlite3_reset(mStatement);
	}

	~CDBCursor() {
		sqlite3_finalize(mStatement);
	}

};

typedef boost::shared_ptr<CDBCursor> DBCursorRef;

class CDBHelper {

	int mVersion;
	std::string mPath;
	boost::shared_mutex mMutex;

public :
	CDBHelper(int version);
	static CDBHelper& GetInstance();

	void Init();
	DBCursorRef Query(std::string& table, std::string& cond, std::string& order);
	bool Insert(CRecord& r);
	bool Delete(CRecord& r);
	bool Update(CRecord& r);
};

} // Common
} // Client

#endif //__CLIENT_COMMON_DBHELPER_included